package com.ducbase.ducsvc;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContactUsServlet extends HttpServlet {
	static private Logger logger = Logger.getLogger(ContactUsServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		// TODO: change this to fetch the form HTML and respond.
		resp.setContentType("text/javascript");
		resp.getWriter().println("GET not supported.");
	}
	
	public void doOptions(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		// When requesting/posting from another domain, Google Chrome seems to use
		// following standard: http://www.w3.org/TR/2008/WD-access-control-20080912
		logger.info("doOptions");
		logger.info(req.toString());
		resp.setContentLength(0); // needs to be 0 as per the spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2
		resp.setStatus(200);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		// TODO: make this method more generic:
		// - fetch fields for email dynamically
		// - resolve to address based on hidden field in the form
		// - ...
		String message = req.getParameter("msg");
		if (message == null || "".equals(message)) {
			logger.severe("Content missing");
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content missing");
		}
		String from = req.getParameter("email");
		if (from == null || "".equals(from)) {
			logger.severe("From missing");
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "From missing");
		}
		String name = req.getParameter("name");
		if (name == null || "".equals(name)) {
			logger.severe("Name missing");
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Name missing");
		}
		this.sendMail(name, from, message);
	}
	
	private void sendMail(String name, String from, String message) {
        String msgBody = "Email from mjelektro.be: \n\n" 
        	+ "Naam: " + name + "\n" 
        	+ "Email: " + from + "\n"
        	+ "Bericht: " + message;
        
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        
        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("tom@ducbase.com", "mjelektro.be"));
            InternetAddress replyTo[] = new InternetAddress[1];
            replyTo[0] = new InternetAddress(from);
            msg.setReplyTo(replyTo);
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("info@mjelektro.be", "Juri Meyvis"));
            msg.setSubject("Contact from mjelektro.be");
            msg.setText(msgBody);
            Transport.send(msg);

        } catch (AddressException e) {
        	logger.log(Level.SEVERE, "AddressException", e);
        } catch (MessagingException e) {
        	logger.log(Level.SEVERE, "MessagingException", e);
        } catch (UnsupportedEncodingException e) {
        	logger.log(Level.SEVERE, "UnsupportedEncodingException", e);
		}
	}
}
